#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstdarg>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATH "./log/"
#define SIZE 1024

#define INFO 0
#define DEBUG 1
#define WARNING 2
#define ERROR 3
#define FATAL 4

#define Screen 1
#define Onefile 2
#define Classfile 3

#define Logtxt "log.txt"

class Log
{
public:
    //构造析构
    Log(){
        printmethod = Screen;
        path = PATH;
    }
    ~Log(){}

    //获取日志等级
    std::string LevelToString(int level)
    {
        switch (level)
        {
        case INFO:
            return "info";
        case DEBUG:
            return "debug";
        case WARNING:
            return "warning";
        case ERROR :
            return "error";
        case FATAL:
            return "fatal";
        default:
            return "none";
        }
    }
    //获取日志信息
    void logmessage(int level, const char *format...)
    {
        return;
    }

    void operator()(int level, const char *format...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char normal[SIZE];
        snprintf(normal, sizeof(normal), "[%s][%d-%d-%d %d-%d-%d]", LevelToString(level).c_str(),
                 ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
                 ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

        va_list s;
        va_start(s, format);
        char abnormal[SIZE];
        vsnprintf(abnormal, sizeof(abnormal), format, s);
        va_end(s);

        // 控制格式
        char logmat[SIZE * 2];
        snprintf(logmat, sizeof(logmat), "%s--%s", normal, abnormal);

        //printf("%s/n", logmat);
        printmode(level,logmat);
    }

    void printmode(int level ,const std::string& msg)
    {
        switch(printmethod)
        {
            case Screen : std::cout << msg <<std::endl;
                break;
            case Onefile : OnefilePrint(Logtxt,msg);
                break;
            case Classfile: ClassfilePrint(level,msg);
            default: 
                break; 
        }

    }


    void OnefilePrint(const std::string& logname ,const std::string& msg)
    {
        std::string log_name = path + logname;
        int fd = open(log_name.c_str(),O_WRONLY|O_CREAT|O_APPEND,0664);
        if(fd == -1) return ;
        write(fd,msg.c_str(),msg.size());
        close(fd);
    }

    void ClassfilePrint(int level ,const std::string& msg)
    {
        std::string log_name = "LogFile";
        log_name += '.';
        log_name += LevelToString(level);
        OnefilePrint(log_name,msg);
    }

private:
    int printmethod = Screen;
    std::string path = PATH;
};

Log lg;
